﻿using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace PasteLoggerBoard
{
    /// <summary>
    /// 
    /// </summary>
    public class PasteLoggerBoardDbContextFactory : IDesignTimeDbContextFactory<PasteLoggerBoardDbContext>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public PasteLoggerBoardDbContext CreateDbContext(string[] args)
        {
            //这个仅仅在EF的时候调用
            //System.Console.WriteLine($"{System.DateTime.Now} PasteLoggerBoardDbContextFactory.CreateDbContext.start");
            System.AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<PasteLoggerBoardDbContext>()
                .UseNpgsql(configuration.GetConnectionString(PasteLoggerBoardDbProperties.ConnectionStringName));
            //    .ReplaceService<IMigrationsSqlGenerator, MyMigrationsSqlGenerator>();
            //System.Console.WriteLine($"{System.DateTime.Now} PasteLoggerBoardDbContextFactory.CreateDbContext.end");
            return new PasteLoggerBoardDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }
    }
}
